#include "head.h"

void *thread_main(void *p)
{
    pthread_info *p_info=(pthread_info *)p;
    
    //------
    int socket_long=socket(AF_INET,SOCK_STREAM,0);
    
    char ip[1000];
    char port[1000];
    getparameter("port",port);
    getparameter("ip",ip);

    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(atoi(port));
    addr.sin_addr.s_addr=inet_addr(ip);
    int con_ret=connect(socket_long,(struct sockaddr*)&addr,sizeof(addr));
    if(con_ret==-1){
        printf("连接失败.\n");
    }
    
    c_sends infos;
    strcpy(infos.token,p_info->send_info.token);
    send(socket_long,&infos,sizeof(infos),MSG_NOSIGNAL);
    recvMsg msg;
    int recv_ret=recv(socket_long,&msg,sizeof(msg),MSG_WAITALL);
    if(strcmp(msg.statu,"1")!=0){
        printf("登录失败.\n");
        pthread_exit(NULL);
    } 
    printf("登录成功.\n");

    p_info->socket_long=socket_long;
    while(1){
        pthread_mutex_lock(&p_info->one.lock);
    
        if(p_info->one.exit_flag==false){
            printf("wait!!!!\n");
            pthread_cond_wait(&p_info->one.cond,&p_info->one.lock);
            printf("dododo\n");
        }

        if(p_info->one.exit_flag==true){
            printf("exit!\n");
            pthread_mutex_unlock(&p_info->one.lock);
            pthread_exit(NULL);
        }

        //处理长命令
        if(p_info->is_gets){
            printf("my_gets:begin.\n");
            my_gets(p_info->send_info,p_info->consumer,p_info->socket_long);
            printf("my_gets:end.\n");

        }else{
            printf("my_puts:begin.\n");
            my_puts(p_info->send_info,p_info->consumer,p_info->socket_long);
            printf("my_puts:end.\n");
        }

        pthread_mutex_unlock(&p_info->one.lock);
    }
    printf("线程处理完毕.\n");
}


int initStatus(pthread_info **p_info)
{
    
    *p_info=(pthread_info*)calloc(1,sizeof(pthread_info));
    
    (*p_info)->one.exit_flag=false;
    pthread_mutex_init(&(*p_info)->one.lock,NULL);
    pthread_cond_init(&(*p_info)->one.cond,NULL);
    pthread_create(&(*p_info)->one.pth_id,NULL,thread_main,(void*)*p_info);
    return 0;
}
